export function hasClass(el, className) {
  let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  return reg.test(el.className)
}

export function addClass(el, className) {
  if (hasClass(el, className)) {
    return
  }

  let newClass = el.className.split(' ')
  newClass.push(className)
  el.className = newClass.join(' ')
}

export function removeClass(el, className) {
  if (hasClass(el, className)) {
    el.classList.remove(className)
  }
}

export function toggleClass(el, className) {
  if (hasClass(el, className)) {
    el.classList.remove(className)
  } else{
    addClass(el, className)
  }
}

let elementStyle = document.createElement('div').style

let vendor = (() => {
  let transformNames = {
    webkit: 'webkitTransform',
    Moz: 'MozTransform',
    O: 'OTransform',
    ms: 'msTransform',
    standard: 'transform'
  }

  for (let key in transformNames) {
    if (elementStyle[transformNames[key]] !== undefined) {
      return key
    }
  }

  return false
})()

export function prefixStyle(style) {
  if (vendor === false) {
    return false
  }

  if (vendor === 'standard') {
    return style
  }

  return vendor + style.charAt(0).toUpperCase() + style.substr(1)
}

export function getData (el, name, val) {
  const prefix = 'data-'
  if (val) {
    return el.setAttribute(prefix + name, val)
  } else {
    return el.getAttribute(prefix + name)
  }
}

// 随机取得字符串

export function randomPrev() {
  let first = Math.random().toString(16).substring(2) //13位
  let second = Math.random().toString(36).substring(2)// 11位
  return first+second
}

// 搜索关键字高亮
export function setHeightKeyWord(id, keyword, color, bold, oldHtml) {
  if (keyword == "")
    return;
  var tempHTML = document.querySelector("#" + id).innerHTML
  var htmlReg = new RegExp("\<.*?\>", "i");
  var arrA = new Array();
  for (var i = 0; true; i++) {
    var m = htmlReg.exec(tempHTML);
    if (m) {
      arrA[i] = m;
    }
    else {
      break;
    }
    tempHTML = tempHTML.replace(m, "[[[[" + i + "]]]]");
  }
  var replaceText
  if (bold)
    replaceText = "<b style='color:" + color + ";'>$1</b>";
  else
    replaceText = "<font style='color:" + color + ";'>$1</font>";
  var arrayWord = keyword.split(',');
  for (var w = 0; w < arrayWord.length; w++) {
    var r = new RegExp("(" + arrayWord[w].replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&") + ")", "ig");
    tempHTML = tempHTML.replace(r, replaceText);
  }
  for (var i = 0; i < arrA.length; i++) {
    tempHTML = tempHTML.replace("[[[[" + i + "]]]]", arrA[i]);
  }
  document.querySelector("#" +id).innerHTML = tempHTML
}
